const Koa = require('koa')
const WebSocket = require('ws');
const fs = require('fs');
const cors = require('koa2-cors')
// 引入路由


const libs = require('./libs');
console.log(libs);
var _File = fs.readFileSync('C:/Users/Administrator/Desktop/DataTest2.SPM');


const router = require("koa-router")();
// 设置路由前缀
// router.prefix("/api");

router.get("/", async function (ctx, next) {
    r = _File.buffer;
    var i = 0;
    var data = {}
    data.str = libs.utf8ArrayToStr(libs.getBit(r, i, i += 4, Uint8Array));
    data.long = libs.getBit(r, i, i += 4, Int32Array)[0]
    data.ansType = libs.getBit(r, i, i += 2, Int16Array)[0]
    data.block = libs.utf8ArrayToStr(libs.getBit(r, i, i += 4, Uint8Array))
    data.version = libs.utf8ArrayToStr(libs.getBit(r, i, i += 2, Uint8Array))
    data.FileLength = libs.getBit(r, i, i += 4, Int32Array)[0]
    data.placeID = libs.utf8ArrayToStr(libs.getBit(r, i, i += 14, Uint8Array))
    data.thingID = libs.utf8ArrayToStr(libs.getBit(r, i, i += 36, Uint8Array))
    data.moduleType = libs.utf8ArrayToStr(libs.getBit(r, i, i += 2, Uint8Array))
    data.Lon = libs.getBit(r, i, i += 8, BigInt64Array)[0].toString();
    data.lat = libs.getBit(r, i, i += 8, BigInt64Array)[0].toString();
    data.height = libs.getBit(r, i, i += 2, Uint16Array)[0]
    var StartDate = libs.getBit(r, i, i += 8, BigInt64Array)[0];
    data.startTime = new Date(parseInt(StartDate * BigInt(1000)));
    data.endTime = libs.getBit(r, i, i += 2, Int16Array)[0]
    data.start = libs.getBit(r, i, i += 8, Float64Array)[0];
    data.end = libs.getBit(r, i, i += 8, Float64Array)[0];
    data.span = libs.getBit(r, i, i += 4, Float32Array)[0];
    data.mode = libs.utf8ArrayToStr(libs.getBit(r, i, i += 2, Uint8Array));
    data.star2 = libs.utf8ArrayToStr(libs.getBit(r, i, i += 4, Uint8Array));
    data.dataLength = libs.getBit(r, i, i += 4, Int32Array)[0];
    ctx.body = data;
});

const app = new Koa()
const ws = new WebSocket.Server({ port: 3001 });

var runderA = (offset, v) => {
    const long = v.getUint32(offset, true);
    var _offset = long + 20;
    console.log(_offset);
    return _offset
}

ws.on('connection', ws => {
    console.log('server connection');
    ws.on('message', msg => { });
    var index = 0;
    var offset = 130;
    var r = _File.buffer;
    var Time = setInterval(() => {
        var data = libs.GetDates(offset, r);
        var _b = r.slice(offset, data.offset);
        const buffer = Buffer.from(_b);
        offset = data.offset;
        ws.send(buffer);
        index++;
        if (index == 220) {
            clearInterval(Time);
            ws.close();
        }
    }, 735)
    ws.on('close', () => {
        clearInterval(Time);
    })
    ws.send('Information from the server');
});


app.use(cors())
app.use(router.routes(), router.allowedMethods());
app.listen(3000)